package org.xtext.runtime.plan;

import is.lill.acre.protocol.RepositoryException;
import is.lill.acre.protocol.RepositoryFactory;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.xtext.runtime.acre.ACREService;
import org.xtext.runtime.cartago.ICartagoPlanStep;
import org.xtext.runtime.interpreter.Agent;
import org.xtext.runtime.term.ITerm;
import org.xtext.runtime.term.Term;
import org.xtext.runtime.term.Variable;
import org.xtext.runtime.util.Bindings;
import org.xtext.runtime.util.EvaluateTermsVisitor;

/**
 * Implements the plan step for invoking an EIS action. 
 * @author rem
 *
 */
public class AcreAddRepositoryStep implements IPlanStep {
	private ITerm repository;
	
	public AcreAddRepositoryStep(ITerm repository) {
		this.repository = repository;
	}
	
	@Override
	public AcreAddRepositoryStep apply(Bindings set) {
		repository = repository.apply(set);
		return this;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void handle(Agent agent, PlanStack planStack) {
		EvaluateTermsVisitor visitor = new EvaluateTermsVisitor(agent);
		Term<String> term = (Term<String>) repository.accept(visitor);
		try {
			ACREService.manager.addRepository( RepositoryFactory.openRepository( term.value().toString() ) );
		} catch (RepositoryException e) {
			e.printStackTrace();
			planStack.fail();
		}
	}

	@Override
	public String toString(String tabs) {
		return tabs + "acre_add_repository(" + repository + ")";
	}
	
	public String toFullString(String tabs) {
		return toString(tabs);
	}
	
	@Override
	public Set<Variable> variables() {
		Set<Variable> vars = new HashSet<Variable>();
		if (repository instanceof Variable) vars.add((Variable) repository);
		return vars;
	}

	@Override
	public IPlanStep copy(Map<String, Variable> vars) {
		return new AcreAddRepositoryStep(repository.copy(vars));
	}

	public String toString() {
		return toString("");
	}

	@Override
	public void reset() {
	}
}
